package cn.ztydata.teachingsystem.heaven.util;

import cn.ztydata.teachingsystem.exception.UtilException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.TypeFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Json转换工具类
 * Created by cx on 2015/4/1.
 */
public class JsonUtil<T> {
    private static final Logger logger = LoggerFactory.getLogger(JsonUtil.class);

    private ObjectMapper mapper;
    private TypeFactory typeFactory;
    private Class<T> clazz;

    public JsonUtil() {
        this.mapper = new ObjectMapper();
        this.typeFactory = mapper.getTypeFactory();
    }

    public JsonUtil(Class<T> clazz) {
        this.clazz = clazz;
        this.mapper = new ObjectMapper();
        this.typeFactory = mapper.getTypeFactory();
    }

    public String convertToString(final Object obj) {
        try {
            logger.debug("object to json string");
            return mapper.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            logger.debug("object to json string exception");
            throw new UtilException("object to json string exception", e);
        }
    }

    public List<T> convertToList(String content) {
        if (content == null || content.isEmpty()) {
            logger.debug("content == null || content.isEmpty()");
            return new ArrayList<>();
        }

        try {
            logger.debug("json string to list");
            return mapper.readValue(content, typeFactory.constructCollectionType(List.class, clazz));
        } catch (IOException e) {
            logger.debug("json string to list exception");
            throw new UtilException("json string to list exception", e);
        }
    }

    public T convertToObject(String content) {
        if (content == null || "".equals(content)) {
            return null;
        }

        try {
            return mapper.readValue(content, clazz);
        } catch (IOException e) {
            throw new UtilException("json string to object exception", e);
        }
    }
}
